const puppeteer = require('puppeteer');
const fs = require('fs-extra');
const fs_node = require('fs');


// https://bsk.aixuexi.com/courseInfo.html#/kejian?lessonId=1127624666&classTypeId=139867&subjectId=3&businessId=139867&businessType=2&lectureRelationship=1
// https://bsk.aixuexi.com/courseInfo.html#/kejian?lessonId=1127626232&classTypeId=140106&subjectId=3&businessId=140106&businessType=2&lectureRelationship=1,
// https://bsk.aixuexi.com/courseInfo.html#/kejian?lessonId=1127626890&classTypeId=140185&subjectId=3&businessId=140185&businessType=2&lectureRelationship=1


async function screenshotDOMElement(page, selector, path, padding = 0) {

    const rect = await page.evaluate(selector => {
        try {
            const element = document.querySelector(selector);
            const { x, y, width, height } = element.getBoundingClientRect();
            if (width * height != 0) {
                return { left: x, top: y, width, height, id: element.id };
            } else {
                return null;
            }
        } catch (e) {
            return null;
        }
    }, selector);

    return await page.screenshot({
        path: path,
        clip: rect ? {
            x: rect.left - padding,
            y: rect.top - padding,
            width: rect.width + padding * 2,
            height: rect.height + padding * 2
        } : null
    });
}

async function tab(browser, urlArr, headless = false, network = 1, logCb, urlIndex) {

    //检测参数有值 
    urlArr = urlArr || [];
    if (urlArr.length == 0) {
        logCb("结束:检测参数无值");
        return;
    }

    var url = urlArr[urlIndex];

    const page = await browser.newPage();

    page.setViewport({
        width: 1280,
        height: 760,
    });

    await page.evaluateOnNewDocument(() => {

        Object.defineProperty(navigator, 'webdriver', {
            get: () => false,
        });

    });

    // var url = "https://slide.aixuexi.com/static-v2/player.html?deck=8ca5ed8f-fec3-4cfd-a061-58f54bc178d6&ratio=0&sdk_version=1.1.20&platform=axx&playSource=ST&platform=bsk&authorityComment=1&slideNum=1&showRandomQuestion=1&disableKeyboard=true&teacherState=1&showPlane=1&supervideo=0&hiddenSlideIndexes=&hideTocBtn=false&hideThumbBtn=false&mathjaxv=1590501171224"
    // https://bsk.aixuexi.com/courseInfo.html#/kejian?lessonId=1127626890&classTypeId=140185&subjectId=3&businessId=140185&businessType=2&lectureRelationship=1



    logCb("跳转到备课页中....");

    await page.goto(url);

    await page.waitForSelector('.lesson-info');

    logCb("已进入到备案页");

    var lessonName = await page.$eval('.lesson-info', el => el.innerText.replace(' ', ''));

    logCb("拿到lesson名：" + lessonName);

    var folder = `./book/${lessonName}`

    if (fs_node.existsSync(folder)) {
        logCb("已存在以lesson名为" + lessonName + '的文件夹,请先删除掉');
        return;
    }

    fs.ensureDirSync(folder);

    logCb("创建以lesson名为" + lessonName + '的文件夹');


    await page.waitForSelector('#kj-area>iframe');
    const iframeUrl = await page.$eval('#kj-area>iframe', el => el.getAttribute('src'));

    logCb("拿到嵌的类PPT网页地址");


    await page.goto(iframeUrl);


    await page.waitForSelector('#play_next_step_button');
    const nextStepBtn = await page.$('#play_next_step_button');

    logCb("已进入嵌的类PPT网页");


    var totalPage = await page.$eval('#controls_slide_count', el => el.innerHTML);
    totalPage = parseInt(totalPage);

    logCb("获取到总页数：" + totalPage);


    logCb("============开始爬取" + lessonName + '===============');

    var currentPage = 0;

    async function next() {

        var currentPageStr = await page.$eval('#controls_slide_cur', el => el.innerHTML);
        currentPage = parseInt(currentPageStr);



        let text = await page.$eval('#play_animation', el => el.innerHTML);

        //当前第几张
        var m = text.split(' ')[1].split('/')[0];

        //共第几张
        var n = text.split(' ')[1].split('/')[1];





        logCb(`开始截取第${currentPage}页，第${m}张`);

        await screenshotDOMElement(page, '#scene', `${folder}/${currentPage}-${m}.png`)

        if (totalPage == currentPage && n == m) {
            logCb(`============${lessonName}截取完成============`);
            await page.close();
            // await browser.close();
            urlIndex = urlIndex + 1;

            if (urlArr.length <= urlIndex) {
                logCb(`============全部截取完成============`);
                // await browser.close();
            } else {
                await tab(browser, urlArr, headless = false, network = 1, logCb, urlIndex)
            }

        }

        console.log(currentPage, totalPage, '进来了')
        await nextStepBtn.click();
        await page.waitFor(2500 * network);
        next();

    }

    await page.waitFor(1000 * network);
    next();



}

async function login(headless = true, network = 1, loginParam, logCb) {

    const browser = await puppeteer.launch({
        headless: headless,
        defaultViewport: {
            // width: 1920 / 1.5,
            // height: 1080 / 1.5,

            width: 1280,
            height: 720 + 40  // 40是底部翻页
        },
        args: [`--window-size=${1280},${760 + 88 + 43}`] // new option
    });

    const page = await browser.newPage();

    page.setViewport({
        width: 1280,
        height: 760,
    });

    await page.evaluateOnNewDocument(() => {

        Object.defineProperty(navigator, 'webdriver', {
            get: () => false,
        });

    });

    logCb("正在打开登陆页...");

    await page.goto('https://www.aixuexi.com/login.html');

    const input_user_name = await page.$("[name=username]");

    logCb("打开登陆页完成...");

    await input_user_name.type(loginParam.username);

    const input_pwd = await page.$('[name=password]');

    logCb("输入登陆名...");

    await input_pwd.type(loginParam.password);

    logCb("输入密码...");

    const loginBtn = await page.$('#submit');

    logCb("点击登陆...");

    await loginBtn.click();

    logCb("正在登陆...");


    // var url = "https://slide.aixuexi.com/static-v2/player.html?deck=8ca5ed8f-fec3-4cfd-a061-58f54bc178d6&ratio=0&sdk_version=1.1.20&platform=axx&playSource=ST&platform=bsk&authorityComment=1&slideNum=1&showRandomQuestion=1&disableKeyboard=true&teacherState=1&showPlane=1&supervideo=0&hiddenSlideIndexes=&hideTocBtn=false&hideThumbBtn=false&mathjaxv=1590501171224"
    // https://bsk.aixuexi.com/courseInfo.html#/kejian?lessonId=1127626890&classTypeId=140185&subjectId=3&businessId=140185&businessType=2&lectureRelationship=1

    await page.waitFor(4000 * network);

    return browser;


}


async function screenDoShot(url, headless = false, network = 1, loginParam, logCb) {

    var urlArr = url.split(',');

    var urlArrSet = [...new Set(urlArr)];

    console.log("检测到共计" + urlArr.length + "个");
    console.log("检测到共计" + urlArrSet.length + "个");

    if(urlArr.length>urlArrSet.length)
    {
        logCb("错误:检测到有重复项");
        return;
    }

   

    var browser = await login(headless, network, loginParam,logCb);

    await tab(browser, urlArr, headless, network, logCb, 0)


    console.log("所有完毕")


}



module.exports = screenDoShot;